package com.hhkj.sms.service.impl;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.Common;
import com.aliyun.teautil.models.RuntimeOptions;
import com.hhkj.sms.common.client.AliDaYuClient;
import com.hhkj.sms.model.AliDaYuParam;
import com.hhkj.sms.model.base.BaseSendParam;
import com.hhkj.sms.service.SmsSendService;
import lombok.extern.slf4j.Slf4j;

/**
 * AliDaYuSmsSendServiceImpl
 *
 * @author HHKJ-SERVER-ZJ
 * @since 2023/10/24 14:40
 */
@Slf4j
public class AliDaYuSmsSendServiceImpl implements SmsSendService {

    @Override
    public void send(String mobile, BaseSendParam body) {
        if (!(body instanceof AliDaYuParam)) {
            throw new RuntimeException("短信参数信息错误");
        }
        AliDaYuParam params = (AliDaYuParam) body;
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        if (!Validator.isMobile(mobile)) {
            throw new RuntimeException("手机号不合法");
        }
        if (StrUtil.isBlank(params.getSignName())
                || StrUtil.isBlank(params.getTemplateCode())) {
            throw new RuntimeException("参数错误");
        }
        sendSmsRequest.setPhoneNumbers(mobile)
                .setSignName(params.getSignName())
                .setTemplateCode(params.getTemplateCode())
                .setTemplateParam(params.getTemplateParam());

        RuntimeOptions runtime = new RuntimeOptions();
        Client client = AliDaYuClient.getInstance();

        try {
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
            log.info(sendSmsResponse.getBody().getMessage());
        } catch (TeaException error) {
            // 如有需要，请打印 error
            Common.assertAsString(error.message);
            log.error(error.message);
            throw new RuntimeException(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            Common.assertAsString(error.message);
            log.error(error.message);
            throw new RuntimeException(error.message);
        }
    }
}
